#include <Ogre.h>
#include "./PvN.h"
#include "../GameLogic/Level/Level.h"
#include "../GameLogic/Simulation.h"

using namespace Core;

PvN::PvN():
	presentation_( Graphics::Presentation::getInstance() )
,	simulation_( 0 )
,	input_( &Input::InputThread::getInstance() )
,	input_thread_( input_ )
{

}

PvN::~PvN() {}

bool PvN::initOgre() {
	return presentation_.init();
}

bool PvN::initOIS() {
	size_t render_window_handle = 0;
	Ogre::RenderWindow* rw = presentation_.getWindow();
	rw->getCustomAttribute("WINDOW", &render_window_handle);
	input_->init( render_window_handle );
	input_->windowResized( rw );
	return true;
}

bool PvN::init() {
	bool result;

	// Inicjuje grafike:
	result = initOgre();

	//Inicjuje wejscie:
	result &= initOIS();

	//uruchamia watek wejscia:
	input_thread_.start();

	return result;

}

#include "../GameLogic/Level/SampleLevelConstructor.h"

GameLogic::MainLoop* PvN::setupGame( bool is_server ) {
	simulation_ = new GameLogic::Simulation( is_server );
	//konstruuje level:

	//przykladowy level:
	GameLogic::Level::Level* level = SampleLevelConstructor();

	//inicjalizuje simulation:
	simulation_->initialize( level );
	presentation_.initializeGame( level );
	GameLogic::MainLoop* ml = new GameLogic::MainLoop( simulation_, is_server );

	if( !is_server )
		Core::GameState::StateMachine::getInstance().setState( Core::GameState::gsSetup );
	else {
		level->deployOnServer();
		Core::GameState::StateMachine::getInstance().setState( Core::GameState::gsIngame );
	}
	return ml;
}

void PvN::beginGame( bool is_server ) {
	GameLogic::MainLoop* game_loop = setupGame( is_server );
	game_loop->enterMainGameLoop();
	delete game_loop;
	delete simulation_;
	simulation_ = 0;
}
